﻿using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

[assembly:TagPrefix("AspDotnetPractice.CustomServerControl","practiceUI")]
namespace AspDotnetPractice.CustomServerControl
{
    [AspNetHostingPermission(SecurityAction.Demand,Level =AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [ToolboxData("<{0}:IndexButton runat=\"server\"></{0}:IndexButton>")]
    [DefaultProperty("Index")]
    public class IndexButton : Button
    {
        private int indexValue;

        [Browsable(true)]
        [Category("Behavior")]
        [DefaultValue(0)]
        [Description("The index stored in control state.")]
        public int Index
        {
            get { return indexValue; }
            set { indexValue = value; }
        }

        [
        Bindable(true),
        Category("Behavior"),
        DefaultValue(0),
        Description("The index stored in view state.")
        ]
        public int IndexInViewState
        {
            get
            {
                object obj = ViewState["IndexInViewState"];
                return (obj == null) ? 0 : (int)obj;
            }
            set { ViewState["IndexInViewState"] = value; }
        }

        protected override void OnInit(System.EventArgs e)
        {
            base.OnInit(e);
            Page.RegisterRequiresControlState(this);
        }

        protected override object SaveControlState()
        {
            object obj = base.SaveControlState();
            if (indexValue != 0)
            {
                return obj != null ? (object) new Pair(obj, indexValue) : indexValue;
            }
            return obj;
        }

        protected override void LoadControlState(object savedState)
        {
            if (savedState != null)
            {
                Pair pair = savedState as Pair;
                if (pair != null)
                {
                    base.LoadControlState(pair.First);
                    indexValue = (int)pair.Second;
                }
                else
                {
                    if (savedState is int)
                    {
                        indexValue = (int) savedState;
                    }
                    else
                    {
                        base.LoadControlState(savedState);
                    }
                }
            }
        }
    }
}
